package org.lex.ftplist.ui;

import java.io.IOException;
import java.util.Arrays;

import javax.swing.ActionMap;
import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.UIManager;

import org.jdesktop.application.Application;
import org.lex.ftplist.ui.action.AboutAction;
import org.lex.ftplist.ui.action.ExitAction;
import org.lex.ftplist.ui.action.NewFtpListAction;
import org.lex.ftplist.ui.action.ViewCacheAction;
import org.lex.ftplist.util.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class FLApplication extends Application {
	public static void main(String[] args) {
		Application.launch(FLApplication.class, args);
	}

	public static FLApplication getInstance() {
		return Application.getInstance(FLApplication.class);
	}

	public ApplicationOperator getOperator() {
		return operator;
	}

	public JFrame getMainFrame() {
		return this.getMainView().getFrame();
	}

	JDesktopPane getDesktopPane() {
		return this.getMainView().getDesktopPane();
	}

	private Logger log = LoggerFactory.getLogger(FLApplication.class);
	private ApplicationOperator operator = new ApplicationOperator();
	private FLMainView mainView = null;

	@Override
	protected void initialize(String[] args) {
		log.info("Application initialize with args=" + Arrays.toString(args));
		super.initialize(args);
		UIManager.put("swing.boldMetal", Boolean.FALSE);
		// init actions
		log.info("init actions");
		ActionMap am = getContext().getActionMap();
		am.put(Actions.exit, new ExitAction());
		am.put(Actions.about, new AboutAction());
		am.put(Actions.newFtpList, new NewFtpListAction());
		am.put(Actions.viewCache, new ViewCacheAction());
	}

	@Override
	protected void startup() {
		log.info("Application startup()");
		try {
			this.getContext().getSessionStorage().restore(getMainFrame(), Constants.SESSION_FILE);
		} catch (IOException e) {
			e.printStackTrace();
		}
		// show main view
		this.getMainFrame().setVisible(true);
	}

	@Override
	protected void ready() {
		log.info("Application ready()");
	}

	@Override
	protected void shutdown() {
		log.info("Application shutdown()");
		try {
			this.getContext().getSessionStorage().save(getMainFrame(), Constants.SESSION_FILE);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	protected void end() {
		log.info("Application end()");
		System.exit(0);
	}

	private FLMainView getMainView() {
		if (null == mainView) {
			mainView = new FLMainView(this);
		}
		return mainView;
	}
}
